package com.itheima.patterns.builderpattern.singleton.reslove2;

import java.io.Serializable;

public class Singleton implements Serializable {
    
    private static boolean flag = false;
    
    //私有构造方法
    private Singleton() {
        synchronized (Singleton.class){
            //若flag的值为true，说明不是第一次访问，直接抛一个异常
            if(flag){
                throw new RuntimeException("不能创建多个对象！");
            }
            flag = true;
        }
    }
    
    private static class SingletonHolder {
        private static final Singleton INSTANCE = new Singleton();
    }
    //对外提供静态方法获取该对象
    public static Singleton getInstance() {
        return SingletonHolder.INSTANCE;
    }
}